// 导入axios
import axios from 'axios'
// 导入json-bigint
import jsonBig from 'json-bigint'
import store from '@/store'

// 定义一个基地址
const request = axios.create({
  baseURL: 'http://ttapi.research.itcast.cn/'
})

// 配置处理后端返回数据中超出 js 安全整数范围问题

request.defaults.transformResponse = [function (data) {
  try {
    return jsonBig.parse(data)
  } catch (err) {
    return {}
  }
}]

// 请求拦截器
request.interceptors.request.use(
  function (config) {
    const user = store.state.user
    if (user) {
      config.headers.Authorization = `Bearer ${user.token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
// 响应拦截器
request.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error)
  }
)
export default request// 导出axios
